import axios from "axios";
// import Vue from 'vue'
// import loginUtil from "./login";
import { message, notification } from "ant-design-vue";
// import { useRouter } from 'vue-router'
import router from "@/router/index.ts";

const pendingRequests = new Map();
const CancelToken = axios.CancelToken;

const serve = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  headers: {
    Authorization: localStorage.getItem("token")
      ? localStorage.getItem("token")
      : "",
  },
});

// const router = useRouter()

const setHeaderToken = () => {
  serve.defaults.headers["Authorization"] = localStorage.getItem("token");
};

serve.interceptors.request.use((config) => {
  const source = CancelToken.source();
  config.cancelToken = source.token;
  pendingRequests.set(config.url, source);
  return config;
});

serve.interceptors.response.use(
  function (response) {
    // Remove from pending requests
    pendingRequests.delete(response.config.url);
    // console.log('response', response)
    switch (response?.data?.code) {
      case -1000:
        // Cancel all pending requests
        pendingRequests.forEach((source, url) => {
          source.cancel("登录超时");
          pendingRequests.delete(url);
        });
        message.error("登录状态已过期");
        localStorage.clear();
        router.push("/login");
        return Promise.reject(response);
      case 401:
        message.error("登录状态已过期");
        return Promise.reject(response); // 直接跳入catch
      case 402:
        message.error("登录状态已过期");
        return;
      case 403:
        message.error("登录状态已过期");
        return;
      case 500:
        message.error("请求错误:500");
        /* setTimeout(() => {
          localStorage.clear()
          console.log('500---location.reload()')
          location.reload()
        }, 2000) */
        return Promise.reject(response);
    }
    if (response?.data?.code == 200) {
      return response.data?.data || "";
    } else {
      console.log("response--else", response);
      if (response?.data) {
        message.error(response.data.msg);
        console.group("业务逻辑错误");
        console.warn(`请求接口：${response.config.url}`);
        if (response.config.params) {
          console.warn(`请求参数：${JSON.stringify(response.config.params)}`);
        }
        console.warn(`错误描述：${response.data.msg}`);
        console.warn(`错误码：${response.data.code}`);
        console.groupEnd();
        return Promise.reject(response);
      }
    }
  },
  function (error) {
    console.log("interceptors-error", error);
    message.error("网络错误");
    return Promise.reject(error);
  }
);
export default serve;
export { setHeaderToken };
